<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图书馆管理系统 - 图书管理</title>
    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <script src="auth.js"></script>
    <script src="permission-control.js"></script>
</head>
<body>
    <!-- 主系统页面 -->
    <div id="mainPage" class="page active">
        <!-- 顶部导航栏 -->
        <header class="header">
            <div class="header-left">
                <button class="sidebar-toggle" onclick="toggleSidebar()">
                    <i class="fas fa-bars"></i>
                </button>
                <h1 class="logo">
                    <i class="fas fa-book"></i>
                    图书馆管理系统
                </h1>
            </div>
            <div class="header-right">
                <div class="notification-icon" onclick="showNotifications()">
                    <i class="fas fa-bell"></i>
                    <span class="notification-badge" id="notificationBadge">0</span>
                </div>
                <div class="user-menu">
                    <span class="user-name" id="currentUserName">管理员</span>
                    <div class="user-dropdown">
                        <button class="dropdown-btn">
                            <i class="fas fa-user-circle"></i>
                            <i class="fas fa-chevron-down"></i>
                        </button>
                        <div class="dropdown-content">
                            <a href="#" onclick="showProfile()">个人资料</a>
                            <a href="#" onclick="changePassword()">修改密码</a>
                            <a href="#" onclick="logout()">退出登录</a>
                        </div>
                    </div>
                </div>
            </div>
        </header>

        <!-- 侧边栏 -->
        <aside class="sidebar" id="sidebar">
            <nav class="sidebar-nav">
                <ul id="sidebarMenu">
                    <!-- 菜单将通过JavaScript动态生成 -->
                </ul>
            </nav>
        </aside>

        <!-- 主内容区域 -->
        <main class="main-content">
            <!-- 图书管理页面 -->
            <div id="books" class="content-page active">
                <div class="page-header">
                    <h2>图书管理</h2>
                    <div class="header-actions">
                        <button class="btn btn-success" onclick="downloadTemplate()">
                            <i class="fas fa-download"></i>
                            下载模板
                        </button>
                        <button class="btn btn-info" onclick="showImportFromPathModal()">
                            <i class="fas fa-upload"></i>
                            批量导入
                        </button>
                        <button class="btn btn-warning" onclick="exportBooksToPath()">
                            <i class="fas fa-file-excel"></i>
                            导出到本地
                        </button>
                        <button class="btn btn-primary" onclick="showAddBookModal()">
                            <i class="fas fa-plus"></i>
                            添加图书
                        </button>
                    </div>
                </div>
                <div class="page-filters">
                    <div class="filter-group">
                        <div class="search-input-group">
                            <input type="text" id="bookSearch" placeholder="搜索图书（书名、作者、ISBN、出版社）..." class="form-control">
                            <button class="btn btn-search" onclick="searchBooks()">
                                <i class="fas fa-search"></i>
                            </button>
                        </div>
                        <div class="category-filter-group">
                            <label for="bookCategoryFilter" class="filter-label">分类筛选：</label>
                            <select id="bookCategoryFilter" class="form-control">
                                <option value="">所有分类</option>
                            </select>
                        </div>
                        <div class="filter-actions">
                            <button class="btn btn-primary" onclick="searchBooks()">
                                <i class="fas fa-search"></i>
                                搜索
                            </button>
                            <button class="btn btn-secondary" onclick="resetSearch()">
                                <i class="fas fa-undo"></i>
                                重置
                            </button>
                        </div>
                    </div>
                </div>
                <div class="table-container">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>ISBN</th>
                                <th>书名</th>
                                <th>作者</th>
                                <th>出版社</th>
                                <th>分类</th>
                                <th>价格</th>
                                <th>库存</th>
                                <th>可借</th>
                                <th>位置</th>
                                <th>状态管理</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="bookTableBody">
                        </tbody>
                    </table>
                </div>
                <div class="pagination" id="bookPagination">
                </div>
                <div class="pagination-tools" id="bookPaginationTools"></div>
            </div>
        </main>
    </div>

    <!-- 模态框 -->
    <div id="modalOverlay" class="modal-overlay">
        <div class="modal modal-content">
            <div class="modal-header">
                <h3 id="modalTitle">标题</h3>
                <button class="modal-close" onclick="closeModal()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="modal-body" id="modalBody">
            </div>
            <div class="modal-footer" id="modalFooter">
            </div>
        </div>
    </div>

    <!-- 加载提示 -->
    <div id="loadingOverlay" class="loading-overlay">
        <div class="loading-spinner">
            <i class="fas fa-spinner fa-spin"></i>
            <p>加载中...</p>
        </div>
    </div>

    <!-- 消息提示 -->
    <div id="messageContainer" class="message-container">
    </div>

    <script>
        // API基础配置
        const API_BASE_URL = 'http://118.31.223.190:8080';

        // 通用API请求函数
        class ApiClient {
            constructor() {
                this.baseURL = API_BASE_URL;
            }

            async request(url, options = {}) {
                const isForm = options && options.body instanceof FormData;
                const headers = isForm ? (options.headers || {}) : { 'Content-Type': 'application/json', ...(options.headers || {}) };
                const config = { headers, ...options };

                try {
                    const response = await fetch(`${this.baseURL}${url}`, config);
                    const data = await response.json();
                    
                    if (!response.ok) {
                        throw new Error(data.message || `HTTP error! status: ${response.status}`);
                    }
                    
                    return data;
                } catch (error) {
                    console.error('API请求失败:', error);
                    throw error;
                }
            }

            async get(url, params = {}) {
                const queryString = new URLSearchParams(params).toString();
                const fullUrl = queryString ? `${url}?${queryString}` : url;
                return this.request(fullUrl, { method: 'GET' });
            }

            async post(url, data = {}) {
                if (data instanceof FormData) {
                    return this.request(url, { method: 'POST', body: data });
                }
                return this.request(url, { method: 'POST', body: JSON.stringify(data) });
            }

            async put(url, data = {}) {
                const options = {
                    method: 'PUT'
                };
                if (data && Object.keys(data).length > 0) {
                    options.body = JSON.stringify(data);
                }
                return this.request(url, options);
            }

            async delete(url) {
                return this.request(url, { method: 'DELETE' });
            }
        }

        // 创建API客户端实例
        const api = new ApiClient();

        // 图书管理API
        const BookAPI = {
            // 创建图书
            createBook: (bookData) => api.post('/api/books', bookData),
            
            // 更新图书
            updateBook: (bookData) => api.put(`/api/books/${bookData.bookId}`, bookData),

            // 删除图书
            deleteBook: (bookId) => api.delete(`/api/books/${bookId}`),
            
            // 获取图书详情
            getBookById: (bookId) => api.get(`/api/books/${bookId}`),
            
            // 分页查询图书
            pageBooks: (page = 1, size = 10, keyword = '', categoryName = '') => 
                api.get('/api/books/page', { page, size, keyword, categoryName }),
            
            
            // 增加图书库存
            increaseStock: (bookId, count) => 
                api.post(`/api/books/${bookId}/increase-stock?count=${count}`),

            // 减少图书库存
            decreaseStock: (bookId, count) => 
                api.post(`/api/books/${bookId}/decrease-stock?count=${count}`),

            // 获取图书状态统计
            getBookStatusStatistics: (bookId) => 
                api.get(`/api/books/${bookId}/status-statistics`),
            
            // 更新图书条目状态
            updateBookItemStatus: (itemId, status, remark) => 
                api.put(`/api/books/items/${itemId}/status?status=${encodeURIComponent(status)}&remark=${encodeURIComponent(remark || '')}`),

            // 批量导入图书（从文件路径）
            importBooksFromPath: (file) => {
                const formData = new FormData();
                formData.append('file', file);
                return api.post('/api/books/importFromPath', formData);
            },

            // 导出图书到本地路径
            exportBooksToPath: (keyword) => api.get(`/api/books/exportToPath?keyword=${encodeURIComponent(keyword || '')}`)
        };

        // 图书条目管理API
        const BookItemAPI = {
            // 获取图书的所有条目
            getBookItemsByBookId: (bookId) => 
                api.get(`/api/book-items/book/${bookId}`),
            
            // 根据状态获取图书条目
            getBookItemsByStatus: (bookId, status) => 
                api.get(`/api/book-items/book/${bookId}/status/${status}`),
            
            // 批量更新图书条目状态
            batchUpdateBookItemStatus: (itemIds, status, remark) => 
                api.put('/api/book-items/batch/status', { itemIds, status, remark }),
            
            // 获取状态选项
            getStatusOptions: () => 
                api.get('/api/book-items/status-options')
        };

        // 图书分类管理API
        const BookCategoryAPI = {
            // 获取所有分类
            getAllCategories: () => api.get('/api/book-categories')
        };

        // 工具函数
        const Utils = {

            // 安全解析整数
            safeParseInt: (value, defaultValue = 0) => {
                if (!value || value.toString().trim() === '') return defaultValue;
                const parsed = parseInt(value.toString().trim());
                return isNaN(parsed) ? defaultValue : parsed;
            },

            // 安全解析必需的整数（用于ID等不能为0的字段）
            safeParseRequiredInt: (value, fieldName = 'ID') => {
                if (!value || value.toString().trim() === '') {
                    throw new Error(`${fieldName}不能为空`);
                }
                const parsed = parseInt(value.toString().trim());
                if (isNaN(parsed) || parsed <= 0) {
                    throw new Error(`${fieldName}必须是有效的正整数`);
                }
                return parsed;
            },

            // 安全解析浮点数
            safeParseFloat: (value, defaultValue = null) => {
                if (!value || value.toString().trim() === '') return defaultValue;
                const parsed = parseFloat(value.toString().trim());
                return isNaN(parsed) ? defaultValue : parsed;
            },
            
            // 显示加载状态
            showLoading: () => {
                const loadingOverlay = document.getElementById('loadingOverlay');
                if (loadingOverlay) {
                    loadingOverlay.classList.add('active');
                }
            },

            // 隐藏加载状态
            hideLoading: () => {
                const loadingOverlay = document.getElementById('loadingOverlay');
                if (loadingOverlay) {
                    loadingOverlay.classList.remove('active');
                }
            },

            // 显示消息提示
            showMessage: (message, type = 'info', duration = 3000) => {
                const messageContainer = document.getElementById('messageContainer');
                if (!messageContainer) return;

                const messageEl = document.createElement('div');
                messageEl.className = `message ${type}`;
                
                const iconMap = {
                    success: 'fas fa-check-circle',
                    error: 'fas fa-exclamation-circle',
                    warning: 'fas fa-exclamation-triangle',
                    info: 'fas fa-info-circle'
                };

                messageEl.innerHTML = `
                    <i class="${iconMap[type] || iconMap.info}"></i>
                    <span>${message}</span>
                    <button class="message-close" onclick="this.parentElement.remove()">
                        <i class="fas fa-times"></i>
                    </button>
                `;

                messageContainer.appendChild(messageEl);

                // 自动移除消息
                setTimeout(() => {
                    if (messageEl.parentElement) {
                        messageEl.remove();
                    }
                }, duration);
            },

            // 格式化金额
            formatMoney: (amount) => {
                if (amount === null || amount === undefined) return '¥0.00';
                return `¥${parseFloat(amount).toFixed(2)}`;
            },

            // 创建分页组件
            createPagination: (currentPage, totalPages, onPageChange) => {
                const pagination = document.createElement('div');
                pagination.className = 'pagination';

                // 上一页按钮
                const prevBtn = document.createElement('button');
                prevBtn.textContent = '上一页';
                prevBtn.disabled = currentPage <= 1;
                prevBtn.onclick = () => onPageChange(currentPage - 1);
                pagination.appendChild(prevBtn);

                // 页码按钮
                const startPage = Math.max(1, currentPage - 2);
                const endPage = Math.min(totalPages, currentPage + 2);

                if (startPage > 1) {
                    const firstBtn = document.createElement('button');
                    firstBtn.textContent = '1';
                    firstBtn.onclick = () => onPageChange(1);
                    pagination.appendChild(firstBtn);

                    if (startPage > 2) {
                        const ellipsis = document.createElement('span');
                        ellipsis.textContent = '...';
                        ellipsis.style.padding = '0.5rem';
                        pagination.appendChild(ellipsis);
                    }
                }

                for (let i = startPage; i <= endPage; i++) {
                    const pageBtn = document.createElement('button');
                    pageBtn.textContent = i;
                    pageBtn.className = i === currentPage ? 'active' : '';
                    pageBtn.onclick = () => onPageChange(i);
                    pagination.appendChild(pageBtn);
                }

                if (endPage < totalPages) {
                    if (endPage < totalPages - 1) {
                        const ellipsis = document.createElement('span');
                        ellipsis.textContent = '...';
                        ellipsis.style.padding = '0.5rem';
                        pagination.appendChild(ellipsis);
                    }

                    const lastBtn = document.createElement('button');
                    lastBtn.textContent = totalPages;
                    lastBtn.onclick = () => onPageChange(totalPages);
                    pagination.appendChild(lastBtn);
                }

                // 下一页按钮
                const nextBtn = document.createElement('button');
                nextBtn.textContent = '下一页';
                nextBtn.disabled = currentPage >= totalPages;
                nextBtn.onclick = () => onPageChange(currentPage + 1);
                pagination.appendChild(nextBtn);

                return pagination;
            }
        };

        // 全局变量
        let currentUser = null;
        let currentPageNum = 1;
        let currentPageSize = 10;

        // 页面初始化
        document.addEventListener('DOMContentLoaded', function() {
            initializeApp();
            setupSearchEvents();
        });

        // 设置搜索事件
        function setupSearchEvents() {
            // 搜索框回车事件
            const searchInput = document.getElementById('bookSearch');
            if (searchInput) {
                searchInput.addEventListener('keypress', function(e) {
                    if (e.key === 'Enter') {
                        searchBooks();
                    }
                });
            }

            // 分类选择器变化事件
            const categoryFilter = document.getElementById('bookCategoryFilter');
            if (categoryFilter) {
                categoryFilter.addEventListener('change', function() {
                    searchBooks();
                });
            }
        }

        // 初始化应用
        function initializeApp() {
            // 使用通用权限检查
            if (!initializePagePermission()) {
                return;
            }
            
            currentUser = authManager.getCurrentUser();
            
            // 生成动态菜单
            generateSidebarMenu();
            
            // 更新用户信息
            document.getElementById('currentUserName').textContent = currentUser.realName || currentUser.username;
            
            // 加载图书分类过滤器
            loadBookCategoryFilter();
            // 加载图书数据
            loadBooks();
        }

        // 检查登录状态
        function checkLoginStatus() {
            const savedUser = localStorage.getItem('currentUser');
            if (savedUser) {
                currentUser = JSON.parse(savedUser);
            }
        }

        // 生成侧边栏菜单
        function generateSidebarMenu() {
            const sidebarMenu = document.getElementById('sidebarMenu');
            if (sidebarMenu) {
                sidebarMenu.innerHTML = authManager.generateSidebarMenu();
            }
        }

        // 切换侧边栏
        function toggleSidebar() {
            const sidebar = document.getElementById('sidebar');
            sidebar.classList.toggle('active');
        }

        // 退出登录
        function logout() {
            currentUser = null;
            localStorage.removeItem('currentUser');
            window.location.href = 'login.html';
            Utils.showMessage('已退出登录', 'info');
        }

        // 显示通知
        function showNotifications() {
            window.location.href = 'notifications.html';
        }

        // 显示个人资料
        function showProfile() {
            Utils.showMessage('个人资料功能开发中', 'info');
        }

        // 修改密码
        function changePassword() {
            Utils.showMessage('修改密码功能开发中', 'info');
        }

        // 加载图书分类过滤器
        async function loadBookCategoryFilter() {
            try {
                const filter = document.getElementById('bookCategoryFilter');
                if (filter) {
                    // 显示加载状态
                    filter.innerHTML = '<option value="">加载分类中...</option>';
                    filter.disabled = true;
                }

                const response = await BookCategoryAPI.getAllCategories();
                if (response.result === 'SUCCESS') {
                    const categories = response.data;
                    if (filter) {
                        filter.innerHTML = '<option value="">所有分类</option>' +
                            categories.map(cat => `<option value="${cat.categoryName}">${cat.categoryName}</option>`).join('');
                        filter.disabled = false;
                    }
                } else {
                    if (filter) {
                        filter.innerHTML = '<option value="">加载分类失败</option>';
                        filter.disabled = true;
                    }
                }
            } catch (error) {
                console.error('Load book category filter error:', error);
                const filter = document.getElementById('bookCategoryFilter');
                if (filter) {
                    filter.innerHTML = '<option value="">加载分类失败</option>';
                    filter.disabled = true;
                }
            }
        }

        // 加载图书数据
        async function loadBooks(page = 1) {
            try {
                Utils.showLoading();
                
                const keyword = document.getElementById('bookSearch')?.value || '';
                const categoryName = document.getElementById('bookCategoryFilter')?.value || '';
                
                const response = await BookAPI.pageBooks(page, currentPageSize, keyword, categoryName);
                
                if (response.result === 'SUCCESS') {
                    renderBookTable(response.data.records);
                    const totalPages = Math.max(1, (response.data && response.data.pages) ? response.data.pages : 1);
                    renderPagination('bookPagination', page, totalPages, loadBooks);
                    renderPaginationTools('bookPaginationTools', totalPages,
                        (n) => { currentPageNum = n; loadBooks(n); },
                        (size) => { currentPageSize = size; currentPageNum = 1; loadBooks(1); }
                    );
                } else {
                    Utils.showMessage(response.message || '加载图书数据失败', 'error');
                    renderPaginationTools('bookPaginationTools', 1,
                        (n) => { currentPageNum = n; loadBooks(n); },
                        (size) => { currentPageSize = size; currentPageNum = 1; loadBooks(1); }
                    );
                }
            } catch (error) {
                Utils.showMessage('加载图书数据失败', 'error');
                console.error('Books load error:', error);
            } finally {
                Utils.hideLoading();
            }
        }

        // 渲染图书表格
        function renderBookTable(books) {
            const tbody = document.getElementById('bookTableBody');
            if (!tbody) return;
            
            tbody.innerHTML = books.map(book => `
                <tr>
                    <td>${book.bookId}</td>
                    <td>${book.isbn}</td>
                    <td>${book.bookName}</td>
                    <td>${book.author}</td>
                    <td>${book.publisher || '-'}</td>
                    <td>${book.categoryName || '-'}</td>
                    <td>${Utils.formatMoney(book.price)}</td>
                    <td>${book.totalCopies}</td>
                    <td>${book.availableCopies}</td>
                    <td>${book.location || '-'}</td>
                    <td>
                        <button class="btn btn-sm btn-info" onclick="showBookStatusManagement(${book.bookId}, '${book.bookName}')">
                            <i class="fas fa-cogs"></i> 状态管理
                        </button>
                    </td>
                    <td>
                        <button class="btn btn-sm btn-primary" onclick="editBook(${book.bookId})">编辑</button>
                        <button class="btn btn-sm btn-warning" onclick="adjustStock(${book.bookId})">调整库存</button>
                        <button class="btn btn-sm btn-danger" onclick="deleteBook(${book.bookId})">删除</button>
                    </td>
                </tr>
            `).join('');
        }

        // 搜索图书
        function searchBooks() {
            currentPageNum = 1;
            loadBooks(1);
        }

        // 重置搜索
        function resetSearch() {
            document.getElementById('bookSearch').value = '';
            document.getElementById('bookCategoryFilter').value = '';
            currentPageNum = 1;
            loadBooks(1);
        }

        // 显示添加图书模态框
        function showAddBookModal() {
            showModal('添加图书', `
                <form id="addBookForm">
                    <div class="form-group">
                        <label for="addIsbn">ISBN</label>
                        <input type="text" id="addIsbn" name="isbn" required>
                    </div>
                    <div class="form-group">
                        <label for="addBookName">书名</label>
                        <input type="text" id="addBookName" name="bookName" required>
                    </div>
                    <div class="form-group">
                        <label for="addAuthor">作者</label>
                        <input type="text" id="addAuthor" name="author" required>
                    </div>
                    <div class="form-group">
                        <label for="addPublisher">出版社</label>
                        <input type="text" id="addPublisher" name="publisher">
                    </div>
                    <div class="form-group">
                        <label for="addPublishDate">出版日期</label>
                        <input type="date" id="addPublishDate" name="publishDate">
                    </div>
                    <div class="form-group">
                        <label for="addCategoryName">分类</label>
                        <select id="addCategoryName" name="categoryName">
                            <option value="">请选择分类</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="addPrice">价格</label>
                        <input type="number" id="addPrice" name="price" step="0.01" min="0">
                    </div>
                    <div class="form-group">
                        <label for="addTotalCopies">总册数</label>
                        <input type="number" id="addTotalCopies" name="totalCopies" min="1" value="1" required>
                    </div>
                    <div class="form-group">
                        <label for="addLocation">位置</label>
                        <input type="text" id="addLocation" name="location">
                    </div>
                    <div class="form-group">
                        <label for="addDescription">描述</label>
                        <textarea id="addDescription" name="description" rows="3"></textarea>
                    </div>
                </form>
            `, '', [
                {
                    text: '取消',
                    class: 'btn-secondary',
                    onclick: 'closeModal()'
                },
                {
                    text: '添加',
                    class: 'btn-primary',
                    onclick: 'submitAddBook()'
                }
            ]);

            // 模态框显示后加载分类数据
            loadCategoriesForSelect();
        }

        // 加载分类到选择框
        async function loadCategoriesForSelect() {
            try {
                const response = await BookCategoryAPI.getAllCategories();
                if (response.result === 'SUCCESS') {
                    const categories = response.data;
                    // 处理添加图书时的分类选择框
                    const addSelect = document.getElementById('addCategoryName');
                    if (addSelect) {
                        addSelect.innerHTML = '<option value="">请选择分类</option>' +
                            categories.map(cat => `<option value="${cat.categoryName}">${cat.categoryName}</option>`).join('');
                    }
                    // 处理编辑图书时的分类选择框
                    const editSelect = document.getElementById('editCategoryName');
                    if (editSelect) {
                        editSelect.innerHTML = '<option value="">请选择分类</option>' +
                            categories.map(cat => `<option value="${cat.categoryName}">${cat.categoryName}</option>`).join('');
                    }
                }
            } catch (error) {
                console.error('Load categories error:', error);
            }
        }

        // 提交添加图书
        async function submitAddBook() {
            const form = document.getElementById('addBookForm');
            const formData = new FormData(form);
            
            const bookData = {
                isbn: formData.get('isbn'),
                bookName: formData.get('bookName'),
                author: formData.get('author'),
                publisher: formData.get('publisher'),
                publishDate: formData.get('publishDate'),
                categoryName: formData.get('categoryName'),
                price: Utils.safeParseFloat(formData.get('price')),
                totalCopies: Utils.safeParseInt(formData.get('totalCopies'), 1),
                location: formData.get('location'),
                description: formData.get('description'),
            };
            
            try {
                Utils.showLoading();
                const response = await BookAPI.createBook(bookData);
                
                if (response.result === 'SUCCESS') {
                    Utils.showMessage('图书添加成功', 'success');
                    closeModal();
                    loadBooks();
                } else {
                    Utils.showMessage(response.message || '添加图书失败', 'error');
                }
            } catch (error) {
                Utils.showMessage(error.message || '添加图书失败', 'error');
            } finally {
                Utils.hideLoading();
            }
        }

        // 编辑图书
        async function editBook(bookId) {
            try {
                Utils.showLoading();
                const response = await BookAPI.getBookById(bookId);
                
                if (response.result === 'SUCCESS') {
                    const book = response.data;
                    showModal('编辑图书', `
                        <form id="editBookForm">
                            <input type="hidden" id="editBookId" name="bookId" value="${book.bookId}">
                            <div class="form-group">
                                <label for="editIsbn">ISBN</label>
                                <input type="text" id="editIsbn" name="isbn" value="${book.isbn}" required>
                            </div>
                            <div class="form-group">
                                <label for="editBookName">书名</label>
                                <input type="text" id="editBookName" name="bookName" value="${book.bookName}" required>
                            </div>
                            <div class="form-group">
                                <label for="editAuthor">作者</label>
                                <input type="text" id="editAuthor" name="author" value="${book.author}" required>
                            </div>
                            <div class="form-group">
                                <label for="editPublisher">出版社</label>
                                <input type="text" id="editPublisher" name="publisher" value="${book.publisher || ''}">
                            </div>
                            <div class="form-group">
                                <label for="editPublishDate">出版日期</label>
                                <input type="date" id="editPublishDate" name="publishDate" value="${book.publishDate || ''}">
                            </div>
                            <div class="form-group">
                                <label for="editCategoryName">分类</label>
                                <select id="editCategoryName" name="categoryName">
                                    <option value="">请选择分类</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label for="editPrice">价格</label>
                                <input type="number" id="editPrice" name="price" step="0.01" min="0" value="${book.price || ''}">
                            </div>
                            <div class="form-group">
                                <label for="editTotalCopies">总册数</label>
                                <input type="number" id="editTotalCopies" name="totalCopies" min="1" value="${book.totalCopies}" required>
                            </div>
                            <div class="form-group">
                                <label for="editLocation">位置</label>
                                <input type="text" id="editLocation" name="location" value="${book.location || ''}">
                            </div>
                            <div class="form-group">
                                <label for="editDescription">描述</label>
                                <textarea id="editDescription" name="description" rows="3">${book.description || ''}</textarea>
                            </div>
                        </form>
                    `, '', [
                        {
                            text: '取消',
                            class: 'btn-secondary',
                            onclick: 'closeModal()'
                        },
                        {
                            text: '保存',
                            class: 'btn-primary',
                            onclick: 'submitEditBook()'
                        }
                    ]);

                    // 模态框显示后加载分类数据
                    loadCategoriesForSelect().then(() => {
                        // 设置选中的分类
                        const categorySelect = document.getElementById('editCategoryName');
                        if (categorySelect && book.categoryName) {
                            categorySelect.value = book.categoryName;
                        }
                    });
                } else {
                    Utils.showMessage(response.message || '获取图书信息失败', 'error');
                }
            } catch (error) {
                Utils.showMessage(error.message || '获取图书信息失败', 'error');
            } finally {
                Utils.hideLoading();
            }
        }

        // 提交编辑图书
        async function submitEditBook() {
            const form = document.getElementById('editBookForm');
            const formData = new FormData(form);
            
            const bookData = {
                bookId: Utils.safeParseRequiredInt(formData.get('bookId'), '图书ID'),
                isbn: formData.get('isbn'),
                bookName: formData.get('bookName'),
                author: formData.get('author'),
                publisher: formData.get('publisher'),
                publishDate: formData.get('publishDate'),
                categoryName: formData.get('categoryName'),
                price: Utils.safeParseFloat(formData.get('price')),
                totalCopies: Utils.safeParseInt(formData.get('totalCopies'), 1),
                location: formData.get('location'),
                description: formData.get('description'),
            };
            
            try {
                Utils.showLoading();
                const response = await BookAPI.updateBook(bookData);
                
                if (response.result === 'SUCCESS') {
                    Utils.showMessage('图书更新成功', 'success');
                    closeModal();
                    loadBooks();
                } else {
                    Utils.showMessage(response.message || '更新图书失败', 'error');
                }
            } catch (error) {
                Utils.showMessage(error.message || '更新图书失败', 'error');
            } finally {
                Utils.hideLoading();
            }
        }

        // 调整库存
        function adjustStock(bookId) {
            showModal('调整库存', `
                <form id="adjustStockForm">
                    <input type="hidden" id="adjustBookId" name="bookId" value="${bookId}">
                    <div class="form-group">
                        <label for="adjustType">调整类型</label>
                        <select id="adjustType" name="type" required>
                            <option value="increase">增加库存</option>
                            <option value="decrease">减少库存</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="adjustCount">调整数量</label>
                        <input type="number" id="adjustCount" name="count" min="1" required>
                    </div>
                </form>
            `, '', [
                {
                    text: '取消',
                    class: 'btn-secondary',
                    onclick: 'closeModal()'
                },
                {
                    text: '确认',
                    class: 'btn-primary',
                    onclick: 'submitAdjustStock()'
                }
            ]);
        }

        // 提交调整库存
        async function submitAdjustStock() {
            const form = document.getElementById('adjustStockForm');
            const formData = new FormData(form);
            
            const bookId = Utils.safeParseRequiredInt(formData.get('bookId'), '图书ID');
            const type = formData.get('type');
            const count = Utils.safeParseRequiredInt(formData.get('count'), '调整数量');

            try {
                Utils.showLoading();
                let response;
                
                if (type === 'increase') {
                    response = await BookAPI.increaseStock(bookId, count);
                } else {
                    response = await BookAPI.decreaseStock(bookId, count);
                }
                
                if (response.result === 'SUCCESS') {
                    Utils.showMessage('库存调整成功', 'success');
                    closeModal();
                    loadBooks();
                } else {
                    Utils.showMessage(response.message || '库存调整失败', 'error');
                }
            } catch (error) {
                Utils.showMessage(error.message || '库存调整失败', 'error');
            } finally {
                Utils.hideLoading();
            }
        }

        // 删除图书
        async function deleteBook(bookId) {
            if (!confirm('确定要删除该图书吗？此操作不可恢复！')) return;
            
            try {
                Utils.showLoading();
                const response = await BookAPI.deleteBook(bookId);
                
                if (response.result === 'SUCCESS') {
                    Utils.showMessage('图书删除成功', 'success');
                    loadBooks();
                } else {
                    Utils.showMessage(response.message || '删除图书失败', 'error');
                }
            } catch (error) {
                Utils.showMessage(error.message || '删除图书失败', 'error');
            } finally {
                Utils.hideLoading();
            }
        }


        // 显示模态框
        function showModal(title, body, size = '', buttons = []) {
            document.getElementById('modalTitle').textContent = title;
            document.getElementById('modalBody').innerHTML = body;

            // 设置模态框大小
            const modalContent = document.querySelector('.modal-content');
            if (modalContent) {
                if (size === 'large') {
                    modalContent.classList.add('large');
                } else if (size === 'medium') {
                    modalContent.classList.add('medium');
                } else {
                    modalContent.classList.remove('large', 'medium');
                }
            }

            // 生成按钮HTML
            let footerHTML = '';
            if (buttons && buttons.length > 0) {
                footerHTML = buttons.map(button =>
                    `<button class="btn ${button.class}" onclick="${button.onclick}">${button.text}</button>`
                ).join('');
            } else {
                footerHTML = '<button class="btn btn-primary" onclick="closeModal()">确定</button>';
            }

            document.getElementById('modalFooter').innerHTML = footerHTML;
            document.getElementById('modalOverlay').classList.add('active');
        }

        // 关闭模态框
        function closeModal() {
            document.getElementById('modalOverlay').classList.remove('active');
        }

        // 渲染分页组件
        function renderPagination(containerId, currentPage, totalPages, onPageChange) {
            const container = document.getElementById(containerId);
            if (!container) return;
            
            if (totalPages <= 1) {
                container.innerHTML = '';
                return;
            }
            
            container.innerHTML = '';
            container.appendChild(Utils.createPagination(currentPage, totalPages, onPageChange));
        }

        // 渲染分页工具栏：跳页与每页条数
        function renderPaginationTools(containerId, totalPages, onJump, onSizeChange) {
            const c = document.getElementById(containerId);
            if (!c) return;
            c.innerHTML = `
                <span>到第</span>
                <input id="${containerId}-jump" type="number" min="1" max="${totalPages}" value="${currentPageNum}" style="width:60px">
                <span>页</span>
                <button id="${containerId}-go" class="btn btn-sm btn-primary">确定</button>
                <span style="margin-left:12px">每页</span>
                <select id="${containerId}-size" style="width:90px">
                    <option ${currentPageSize==10?'selected':''} value="10">10 条/页</option>
                    <option ${currentPageSize==20?'selected':''} value="20">20 条/页</option>
                    <option ${currentPageSize==50?'selected':''} value="50">50 条/页</option>
                    <option ${currentPageSize==100?'selected':''} value="100">100 条/页</option>
                </select>
            `;
            const goBtn = document.getElementById(`${containerId}-go`);
            const jumpInput = document.getElementById(`${containerId}-jump`);
            const sizeSelect = document.getElementById(`${containerId}-size`);
            if (goBtn && jumpInput) {
                goBtn.onclick = () => {
                    const n = Utils.safeParseInt(jumpInput.value, 1);
                    const page = Math.min(Math.max(1, n), totalPages);
                    onJump(page);
                };
            }
            if (sizeSelect) {
                sizeSelect.onchange = () => {
                    const size = Utils.safeParseInt(sizeSelect.value, 10);
                    onSizeChange(size);
                };
            }
        }

        // 状态管理相关函数
        let currentBookId = null;
        let currentBookName = '';
        let statusOptions = [];

        // 显示图书状态管理模态框
        async function showBookStatusManagement(bookId, bookName) {
            currentBookId = bookId;
            currentBookName = bookName;

            try {
                Utils.showLoading();

                // 获取状态选项
                const statusResponse = await BookItemAPI.getStatusOptions();
                statusOptions = statusResponse.data || [];

                // 获取图书条目列表
                const itemsResponse = await BookItemAPI.getBookItemsByBookId(bookId);
                const bookItems = itemsResponse.data || [];

                // 获取状态统计
                const statsResponse = await BookAPI.getBookStatusStatistics(bookId);
                const statistics = statsResponse.data || {};

                showBookStatusModal(bookItems, statistics);

            } catch (error) {
                console.error('获取图书状态信息失败:', error);
                Utils.showMessage('获取图书状态信息失败: ' + (error.message || '未知错误'), 'error');
            } finally {
                Utils.hideLoading();
            }
        }

        // 显示图书状态管理模态框
        function showBookStatusModal(bookItems, statistics) {
            const statusStats = statistics.statusStatistics || {};

            showModal(`图书状态管理 - ${currentBookName}`, `
                <div class="book-status-management">
                    <div class="status-statistics">
                        <h4>状态统计</h4>
                        <div class="stats-grid">
                            ${Object.entries(statusStats).map(([status, info]) => `
                                <div class="stat-item">
                                    <span class="stat-label">${info.desc || status}:</span>
                                    <span class="stat-value">${info.count || 0}</span>
                                </div>
                            `).join('')}
                        </div>
                    </div>

                    <div class="book-items-list">
                        <h4>图书条目列表</h4>
                        <div class="items-table-container">
                            <table class="items-table">
                                <thead>
                                    <tr>
                                        <th><input type="checkbox" id="selectAllItems" onchange="toggleSelectAllItems()"></th>
                                        <th>条目ID</th>
                                        <th>状态</th>
                                        <th>备注</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="bookItemsTableBody">
                                    ${bookItems.map(item => `
                                        <tr>
                                            <td><input type="checkbox" class="item-checkbox" value="${item.itemId}"></td>
                                            <td>${item.itemId}</td>
                                            <td>
                                                <span class="status-badge status-${item.status}">
                                                    ${getStatusDesc(item.status)}
                                                </span>
                                            </td>
                                            <td>${item.remark || '-'}</td>
                                            <td>
                                                <button class="btn btn-sm btn-primary" onclick="editItemStatus(${item.itemId}, '${item.status}', '${item.remark || ''}')">
                                                    编辑状态
                                                </button>
                                            </td>
                                        </tr>
                                    `).join('')}
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <div class="batch-operations">
                        <h4>批量操作</h4>
                        <div class="batch-controls">
                            <select id="batchStatusSelect" class="form-control">
                                <option value="">选择状态</option>
                                ${statusOptions.map(option => `
                                    <option value="${option.code}">${option.desc}</option>
                                `).join('')}
                            </select>
                            <input type="text" id="batchRemark" placeholder="备注信息" class="form-control">
                            <button class="btn btn-warning" onclick="batchUpdateStatus()">批量更新状态</button>
                        </div>
                    </div>
                </div>
            `, 'large');
        }

        // 获取状态描述
        function getStatusDesc(status) {
            const option = statusOptions.find(opt => opt.code === status);
            return option ? option.desc : status;
        }

        // 切换全选
        function toggleSelectAllItems() {
            const selectAll = document.getElementById('selectAllItems');
            const checkboxes = document.querySelectorAll('.item-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = selectAll.checked;
            });
        }

        // 编辑单个条目状态
        function editItemStatus(itemId, currentStatus, currentRemark) {
            showModal('编辑图书条目状态', `
                <form id="editItemStatusForm">
                    <div class="form-group">
                        <label for="editItemStatus">状态</label>
                        <select id="editItemStatus" name="status" required>
                            ${statusOptions.map(option => `
                                <option value="${option.code}" ${option.code === currentStatus ? 'selected' : ''}>
                                    ${option.desc}
                                </option>
                            `).join('')}
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="editItemRemark">备注</label>
                        <textarea id="editItemRemark" name="remark" rows="3">${currentRemark}</textarea>
                    </div>
                </form>
            `, 'medium', [
                {
                    text: '取消',
                    class: 'btn-secondary',
                    onclick: 'closeModal()'
                },
                {
                    text: '保存',
                    class: 'btn-primary',
                    onclick: `saveItemStatus(${itemId})`
                }
            ]);
        }

        // 保存条目状态
        async function saveItemStatus(itemId) {
            try {
                const status = document.getElementById('editItemStatus').value;
                const remark = document.getElementById('editItemRemark').value;

                if (!status) {
                    Utils.showMessage('请选择状态', 'error');
                    return;
                }

                Utils.showLoading();

                await BookAPI.updateBookItemStatus(itemId, status, remark);

                Utils.showMessage('状态更新成功', 'success');
                closeModal();

                // 重新加载状态管理页面
                await showBookStatusManagement(currentBookId, currentBookName);

            } catch (error) {
                console.error('更新状态失败:', error);
                Utils.showMessage('更新状态失败: ' + (error.message || '未知错误'), 'error');
            } finally {
                Utils.hideLoading();
            }
        }

        // 批量更新状态
        async function batchUpdateStatus() {
            try {
                const selectedCheckboxes = document.querySelectorAll('.item-checkbox:checked');
                if (selectedCheckboxes.length === 0) {
                    Utils.showMessage('请选择要更新的条目', 'error');
                    return;
                }

                const status = document.getElementById('batchStatusSelect').value;
                if (!status) {
                    Utils.showMessage('请选择状态', 'error');
                    return;
                }

                const remark = document.getElementById('batchRemark').value;
                const itemIds = Array.from(selectedCheckboxes).map(cb => Utils.safeParseInt(cb.value));

                Utils.showLoading();

                await BookItemAPI.batchUpdateBookItemStatus(itemIds, status, remark);

                Utils.showMessage(`成功更新 ${itemIds.length} 个条目的状态`, 'success');

                // 重新加载状态管理页面
                await showBookStatusManagement(currentBookId, currentBookName);

            } catch (error) {
                console.error('批量更新状态失败:', error);
                Utils.showMessage('批量更新状态失败: ' + (error.message || '未知错误'), 'error');
            } finally {
                Utils.hideLoading();
            }
        }


        // 显示批量导入模态框
        function showImportFromPathModal() {
            showModal('批量导入图书', `
                <div class="import-container">
                    <div class="import-tips">
                        <h4>导入说明：</h4>
                        <ul>
                            <li>使用改进的Excel解析引擎，支持更好的数据验证</li>
                            <li>支持.xlsx和.xls格式的Excel文件</li>
                            <li>必填字段：ISBN号、图书名称、作者、分类名称、总册数</li>
                            <li>如果ISBN已存在，将自动增加库存数量</li>
                            <li><strong>如果分类不存在，系统将自动创建新分类</strong></li>
                            <li>提供详细的导入结果统计</li>
                        </ul>
                    </div>
                    <div class="import-form">
                        <div class="form-group">
                            <label for="importFromPathFile">选择Excel文件</label>
                            <input type="file" id="importFromPathFile" accept=".xlsx,.xls" class="form-control">
                        </div>
                    </div>
                </div>
            `, 'medium', [
                {
                    text: '取消',
                    class: 'btn-secondary',
                    onclick: 'closeModal()'
                },
                {
                    text: '开始导入',
                    class: 'btn-primary',
                    onclick: 'importBooksFromPath()'
                }
            ]);
        }


        // 批量导入函数
        async function importBooksFromPath() {
            const fileInput = document.getElementById('importFromPathFile');
            const file = fileInput.files[0];

            if (!file) {
                Utils.showMessage('请选择要导入的Excel文件', 'error');
                return;
            }

            // 检查文件类型
            const fileName = file.name;
            if (!fileName.endsWith('.xlsx') && !fileName.endsWith('.xls')) {
                Utils.showMessage('请选择Excel文件(.xlsx或.xls格式)', 'error');
                return;
            }

            try {
                Utils.showLoading();

                const response = await BookAPI.importBooksFromPath(file);

                if (response.success) {
                    Utils.showMessage(response.data, 'success');
                    closeModal();
                    loadBooks(); // 重新加载图书列表
                } else {
                    Utils.showMessage(response.message || '导入失败', 'error');
                }

            } catch (error) {
                console.error('导入失败:', error);
                Utils.showMessage('导入失败: ' + (error.message || '未知错误'), 'error');
            } finally {
                Utils.hideLoading();
            }
        }

        // 导出到本地路径
        async function exportBooksToPath() {
            try {
                Utils.showLoading();

                const keyword = document.getElementById('bookSearch').value;
                const response = await BookAPI.exportBooksToPath(keyword);

                if (response.success) {
                    Utils.showMessage(`导出成功！文件已保存到: ${response.data}`, 'success');
                } else {
                    Utils.showMessage(response.message || '导出失败', 'error');
                }

            } catch (error) {
                console.error('导出失败:', error);
                Utils.showMessage('导出失败: ' + (error.message || '未知错误'), 'error');
            } finally {
                Utils.hideLoading();
            }
        }

        async function downloadTemplate() {
            try {
                Utils.showLoading();

                // 创建下载链接
                const url = '/api/books/template';
                const link = document.createElement('a');
                link.href = url;
                link.download = '图书导入模板_' + new Date().getTime() + '.xlsx';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);

                Utils.showMessage('模板下载成功', 'success');

            } catch (error) {
                console.error('下载模板失败:', error);
                Utils.showMessage('下载模板失败: ' + (error.message || '未知错误'), 'error');
            } finally {
                Utils.hideLoading();
            }
        }
    </script>
</body>
</html>
